package com.example.culture.util.iputil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @ClassName AddressUtils
 * @Description TODO   获取客户端所在地址工具类
 * @Author lvyongwei
 * @Date 2020-06-11 15:36
 **/
public class AddressUtils {

    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    /**
     * 淘宝根据ip查询地址api
     *
     * 限制不能使用
     */
    //http://ip.taobao.com/service/getIpInfo.php?ip=

    //public static final String IP_URL = "http://ip-api.com/json/?lang=zh-CN";  直接获取ip


    //http://ip-api.com/json/115.191.200.34?lang=zh-CN
    /**
     * 地址中的ipaddress是替换实际ip的值，真实如上
     */
    public static final String IP_URL = "http://ip-api.com/json/ipaddress?lang=zh-CN";


    /**
     * 根据ip地址获取实际请求地址
     * @param ip   请求ip
     * @return
     */
    public static String getAddressByIp(String ip){
        String address=getAddresses(ip,"utf-8");
        if(address==null){
            return "地址未知";
        }
        StringBuilder sb=new StringBuilder();
        try {
            JSONObject country = JSON.parseObject(address);
            if(country.getString("country")!=null || !country.getString("country").equals("")){
                sb.append(country.getString("country")+" ");
            }else if(country.getString("regionName")!=null || !country.getString("regionName").equals("")){
                sb.append(country.getString("regionName")+" ");
            }else if(country.getString("city")!= null || !country.getString("city").equals("")){
                sb.append(country.getString("city"));
            }else{
                return "地址未知";
            }
        } catch (Exception e) {
            log.error("未获取到地址");
            return "地址未知";
        }
        return sb.toString();
    }

    public static String getAddresses(String content, String encodingString) {
        String url=IP_URL.replace("ipaddress",content);
        String returnStr = getResult(url, encodingString);
        if (returnStr != null) {
            // 处理返回的省市区信息
            return returnStr;
        }
        return null;
    }

    /**
     * @param urlStr   请求的地址
     * @param encoding 服务器端请求编码。如GBK,UTF-8等
     * @return
     */
    private static String getResult(String urlStr, String encoding) {
        URL url = null;
        HttpURLConnection connection = null;
        try {
            url = new URL(urlStr);
            // 新建连接实例
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接超时时间，单位毫秒
            connection.setConnectTimeout(8000);
            // 设置读取数据超时时间，单位毫秒
            connection.setReadTimeout(8000);
            // 是否打开输出流 true|false
            connection.setDoOutput(true);
            // 是否打开输入流true|false
            connection.setDoInput(true);
            // 提交方法POST|GET
            connection.setRequestMethod("POST");
            // 是否缓存true|false
            connection.setUseCaches(false);
            connection.connect();// 打开连接端口
            // 往对端写完数据对端服务器返回数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), encoding));
            // ,以BufferedReader流来读取
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
            return buffer.toString();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (connection != null) {
                connection.disconnect();// 关闭连接
            }
        }
        return null;
    }
}
